package com.baseproject;

import com.baseproject.datasource.ConfigParamsSubscriber;
import com.baseproject.rx.OnErrorHandler.BaseErrorHandler;
import com.baseproject.rx.OnErrorHandler.IErrorStateListener;
import com.baseproject.util.LogUtils;
import com.baseproject.util.NetworkUtils;

import java.lang.reflect.Type;

import rx.Subscriber;

/**
 * Created by hp on 2017/6/13.
 */

public abstract class RxSubscriber<T> extends Subscriber<T> implements IErrorStateListener{
    ConfigParamsSubscriber mConfigParamsSubscriber = new ConfigParamsSubscriber();
    IRxSubscriberView mIRxSubscriberView;

    public ConfigParamsSubscriber getConfigParamsSubscriber() {
        return mConfigParamsSubscriber;
    }

    public RxSubscriber setConfigParamsSubscriber(ConfigParamsSubscriber mConfigParamsSubscriber) {
        this.mConfigParamsSubscriber = mConfigParamsSubscriber;
        return this;
    }

    public IRxSubscriberView getIRxSubscriberView() {
        return mIRxSubscriberView;
    }

    public RxSubscriber(IRxSubscriberView mIRxSubscriberView) {
        this.mIRxSubscriberView = mIRxSubscriberView;
        mType = getSuperclassTypeParameter(getClass());
    }

    Type mType;

    Type getSuperclassTypeParameter(Class<?> subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        return superclass;
    }

    @Override
    public void onCompleted() {
        LogUtils.d("onCompleted!");
        onFinally();
    }

    @Override
    public void onError(Throwable e) {
//        LogUtils.e("onError! Stack: " + android.util.Log.getStackTraceString(e));
        finishRefreshing();
        if (!NetworkUtils.showHintIfNetworkNotAvailable(e)) {
            //网络正常，处理手动抛出的异常(如未登录，未订购)
            BaseErrorHandler.createErrorHandler(e).handleError(mConfigParamsSubscriber, mIRxSubscriberView, this);
        }
        onFinally();
    }

    @Override
    public void onNext(T t) {
        LogUtils.d("t = " + t + " mType = " + mType.toString());
        if (null != mIRxSubscriberView && null != t) {
            _onNext(t);
        } else if (null == mIRxSubscriberView) {
            LogUtils.logCatchedException(new Throwable("mView is null!"));
        } else if (null == t) {//说明服务器返回的code正常，只是内容确实没有
            LogUtils.logCatchedException(new Throwable("t is null!"), 2);
            _onNext(t);
        }
        finishRefreshing();
    }

    private void finishRefreshing() {
        if (null != mIRxSubscriberView.getRefresh()) {
            mIRxSubscriberView.getRefresh().finishRefreshing();
            mIRxSubscriberView.getRefresh().finishLoadMore();
        }
    }

    public abstract void _onNext(T t);

    @Override
    public void haveShowLogin() {

    }

    @Override
    public void haveShowOrder() {

    }

    protected void onFinally() {

    }
}
